package com.lmind.core.gps.terminal.protocol;

import java.nio.ByteBuffer;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lmind.core.gps.terminal.message.AbstractMessage;

public class JsonMessageCodec {
	
	private Gson gson = new Gson();
	
//	public byte[] encode(AbstractMessage message) throws Exception {
//		String json = gson.toJson(message);
//		return json.getBytes("utf-8");
//	}
	
	public ByteBuffer encode(AbstractMessage message) throws Exception {
		String json = gson.toJson(message);
		return ByteBuffer.wrap(json.getBytes("utf-8"));
	}
	
//	public AbstractMessage decode(byte[] data) throws Exception {
//		String json = new String(data, "utf-8");
//		JsonObject o = (JsonObject)new JsonParser().parse(json);
//		String name = o.get("name").getAsString();
//		
//		String pkgName = "com.lmind.core.gps.terminal.message";
//		String className = name.substring(0, 1).toUpperCase() + name.substring(1) + "Message";
//		AbstractMessage r = (AbstractMessage)gson.fromJson(o, Class.forName(pkgName + "." + className));
//		return r;
//	}
	
	public AbstractMessage decode(ByteBuffer buff) throws Exception {
		
		byte[] data = new byte[buff.remaining()];
		buff.get(data);
		
		String json = new String(data, "utf-8");
		JsonObject o = (JsonObject)new JsonParser().parse(json);
		String name = o.get("name").getAsString();
		
		String pkgName = "com.lmind.core.gps.terminal.message";
		String className = name.substring(0, 1).toUpperCase() + name.substring(1) + "Message";
		AbstractMessage r = (AbstractMessage)gson.fromJson(o, Class.forName(pkgName + "." + className));
		return r;
	}
	
//	public static void main(String[] args) {
//		try {
//			byte[] data = "{\"name\":\"location\",\"location\":{\"latitude\":110,\"longitude\":40}}".getBytes("utf-8");
//			new JsonMessageCodec().decode(data);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//	}
}
